// Package i18n
// @File: i18n.go
// @Description: i18n
// @Author: YaoRuiQi
// @Date: 2025/8/23 02:53

package i18n

import (
	"GinStandardTemplate/config"
	"GinStandardTemplate/internal/pkg/contextUtils"
	"GinStandardTemplate/utils/logger"
	"GinStandardTemplate/utils/pathUtils"
	"fmt"
	"path/filepath"

	"github.com/nicksnyder/go-i18n/v2/i18n"
	"github.com/pelletier/go-toml/v2"
	"go.uber.org/zap"
	"golang.org/x/text/language"
)

var (
	Bundle            = i18n.NewBundle(language.Chinese)
	SupportedLanguage = []language.Tag{
		language.Chinese,
		language.English,
	}
	LanguageMatcher = language.NewMatcher(SupportedLanguage)
)

// InitI18n
//
//	@Description: 初始化i18n
func InitI18n() {
	Bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal)

	for _, lang := range SupportedLanguage {
		activeFilePath := filepath.Join(config.GlobalConfig.Path.I18nLocalesDir, fmt.Sprintf("active.%s.toml", lang))
		if exists, err := pathUtils.PathExists(activeFilePath); err != nil {
			logger.Logger.Fatal("无法检测i18n文件是否存在", zap.Error(err), zap.String("path", activeFilePath))
		} else if !exists {
			logger.Logger.Fatal("i18n文件不存在", zap.String("lang", lang.String()), zap.String("path", activeFilePath))
		}
		if _, err := Bundle.LoadMessageFile(activeFilePath); err != nil {
			logger.Logger.Fatal("无法加载i18n文件", zap.Error(err), zap.String("path", activeFilePath))
		}
	}
}

// NewI18nLocalizer
//
//	@Description: 新建i18n本地化器
func NewI18nLocalizer(lang string) *i18n.Localizer {
	return i18n.NewLocalizer(Bundle, lang)
}

// GetMessage
//
//	@Description: 获取i18n结果
//	@param messageID 消息ID
//	@param templateData 模板数据
func GetMessage(ctx *contextUtils.RequestContext, messageID string, templateData map[string]interface{}) string {
	if msg, err := ctx.Localizer.Localize(&i18n.LocalizeConfig{
		MessageID:    messageID,
		TemplateData: templateData,
	}); err != nil {
		ctx.Logger.Error(
			"无法获取i18n结果",
			zap.Error(err),
			zap.String("messageID", messageID),
			zap.Any("templateData", templateData),
		)
		return ""
	} else {
		return msg
	}
}
